<template>
    <div class="pack">
        <video controls name="media" class="video" ref="video">
            <source src="http://dict.youdao.com/dictvoice?audio=apple" type="audio/mpeg" />
        </video>
    </div>
</template>

<script>
class readTask {
    constructor(text, delay, playRate) {
        this.text = text;
        this.delay = delay;
        this.playRate = playRate;
    }
}

export default {
    data() {
        return {
            videoSrc: "http://dict.youdao.com/dictvoice?audio=",
            readList: []
        };
    },
    methods: {
        getSrc(text) {
            return `${this.videoSrc}${text}`;
        },
        clearAllTimeout() {
            var highestTimeoutId = setTimeout(";");
            for (var i = 0; i < highestTimeoutId; i++) {
                clearTimeout(i);
            }
        },
        start() {
            let video = this.$refs.video;
            video.src = null;
            video.load();
            this.clearAllTimeout();
            this.readList = [];
            return this;
        },
        read(text, playRate) {
            let task = new readTask(text, null, playRate);
            this.readList.push(task);
            return this;
        },
        delayRead(delay, text, playRate) {
            let task = new readTask(text, delay, playRate);
            this.readList.push(task);
            return this;
        },
        play(callback) {
            let self = this;
            // 弹出一段要播放的文本, 下面逻辑会递归弹出调用
            let task = this.readList.shift();
            if (task == null) { 
                if(callback) { callback() }
                return;
            }

            let video = this.$refs.video;
            video.src = null;
            video.load();
            video.src = this.getSrc(task.text);
            video.playbackRate = task.playRate == null ? 1 : task.playRate;
            if (task.delay != null) {
                setTimeout(() => {
                    video.play().then(() => {
                        let delay =
                            (video.duration * 1000) / (1 * video.playbackRate);
                        let seed = setTimeout(() => {
                            self.play(callback);
                        }, delay);
                    });
                }, task.delay);
            } else {
                video.play().then(() => {
                    let delay =
                        (video.duration * 1000) / (1 * video.playbackRate);
                    setTimeout(() => {
                        self.play(callback);
                    }, delay);
                });
            }
        }
    }
};
</script>

<style scoped>
.pack {
    display: none;
}
</style>